//
// Created by benxb on 2021/11/27.
//

#ifndef BENXDB_DATA_CHUNK_IO_H
#define BENXDB_DATA_CHUNK_IO_H

#include <unordered_map>
#include <queue>
#include "storage/disk/data_chunk_storage.h"
#include "storage/disk/data_chunk_desc.h"
#include "storage/disk/data_chunk_delete_bitmap.h"
#include "storage/data_chunk.h"

namespace benxdb {

/**
 * This class is for data_ chunk read and write.
 * Also it support batch delete.
 */
class DataChunkIO {
public:
    explicit DataChunkIO(const std::string& table_name);
    ~DataChunkIO() = default;

    /**
     * write new chunk into disk
     * @param data_chunk data_ chunk pointer
     * @return
     */
    bool AppendDataChunk(DataChunk* data_chunk, bool need_compress = false);

    void ExpandDeleteMap();

    /**
     * batch delete record id
     * @param record_ids record id vector
     * @return
     */
    bool DeleteRecords(const std::vector<uint64_t>& record_ids);

    /**
     * Read chunk data_ from disk
     * @param chunk_id id of the chunk
     * @return
     */
    DataChunk* ReadDataChunk(chunk_id_t chunk_id);

    /**
     * Read chunk desc from disk
     * @param chunk_id
     * @return
     */
    bool ReadDataChunkDesk(chunk_id_t chunk_id, ChunkDesc& desc);

    /**
     * After use the chunk, it is need to call this function to recycle the data_ chunk
     * @param chunk_id
     */
    void UnPin(chunk_id_t chunk_id);

    void DeleteTableFile();
private:
    // data_ file storage
    DataChunkStorage data_storage_;
    // data_ desc file io
    DataChunkDescIO desc_storage_;
    // data_ delete map file io
    DataChunkDeleteBitmap bitmap_storage_;

    // support for buffer data_ chunk
    std::unordered_map<chunk_id_t, DataChunk*> loaded_chunk_map_;
    // free data_ chunk
    std::deque<DataChunk*> free_chunk_list_;
    // data_ chunk buffer
    DataChunk chunk_buffer_pool_[CHUNK_BUFFER_COUNT];
};

}


#endif //BENXDB_DATA_CHUNK_IO_H
